<?php
/**
 * PaperController
 *
 * PHP Version 5.4
 *
 * @author liuxuTJ <liuxuphp@icesmart.cn>
 */
namespace Admin\Controller;

use Admin\Service\PermissionService;
use Admin\Service\UserService;
use Model\PaperModel;
use Model\PaperResultsModel;
use Model\QuestionModel;
use Model\QuestionTagModel;
use Think\Controller;

/**
 * Class AnswerController
 */
class AnswerController extends BaseController
{

    public function __construct()
    {
        parent::__construct();
        $userService = new UserService();
        $userInfo = $userService->validateLogin();   //验证是否登录

        $permissionService = new PermissionService();
        $permission = $permissionService->validate($userInfo['userId'], [
            'Info' => '/'.CONTROLLER_NAME.'/Info',
        ]);

        $menu = $permissionService->menu($userInfo['userId']);
        $this->assign('menu', $menu);
        $this->assign('permission', $permission);
        $this->assign('userInfo', $userInfo);
    }

    public function index(){
        $model = new PaperResultsModel();
        $count      = $model->count();
        $Page       = new \Think\Page($count,20);
        $show = $Page->show();
        $list = $model->
                 table("paper_results pr,live_rooms rooms,paper pp,users us")->
                 where("`pr`.roomId = `rooms`.id AND `pr`.paperId = `pp`.id AND `pr`.userId = `us`.id")->
                 limit($Page->firstRow.','.$Page->listRows)->
                 field("pr.*,rooms.name as rname,pp.name as pname,us.nickname")->
                 select();
        $this->assign('list', $list);
        $this->assign("page", $show);
        $this->display();
    }

    public function answerInfo(){
        $id = I("get.id");
        $model = new PaperResultsModel();
        $results =$model->
        table("paper_results pr,live_rooms rooms,paper pp,users us")->
        where("`pr`.roomId = `rooms`.id AND `pr`.paperId = `pp`.id AND `pr`.userId = `us`.id AND `pr`.id = {$id}")->
        field("pr.*,rooms.name as rname,pp.name as pname,us.nickname")->
        find();
        $results['question'] = json_decode($results['question'],true);
        $results['answer'] = json_decode($results['answer'],true);
        $scorce = $this->getScores($results['question'],$results['answer']);
        $this->assign("scorce",$scorce);
        print_r($results);
        $this->assign("results",$results);
        $this->display();
    }

    /**
     * @about 计算用户考试成绩
     *
     * @param array $question question
     * @param array $answer answer
     */
    public function getScores($question,$answer){

        $scores = 0;

        foreach($question as $k=>$v){
            if($v['answer'] == $answer[$k]){
                $scores += $v['score'];
            }
        }

        return $scores;

    }


}